//
//  UIimage+Extension.swift
//  WeiBo
//
//  Created by 张德华 on 7/28/16.
//  Copyright © 2016 ZhangDeHua. All rights reserved.
//

import UIKit

extension UIImage {
    
    
    // MARK: - ************获取截屏结果
    static func getScreenShot() -> UIImage {
        
        ///------ 获取到windows
        let windows = UIApplication.sharedApplication().keyWindow!
        
        ///------ 开启上下文
        UIGraphicsBeginImageContext(windows.bounds.size)
        
        ///------ windows渲染到上下文中
        windows.drawViewHierarchyInRect(windows.bounds, afterScreenUpdates: false)
        
        ///------ 从上下文中获取image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        ///------ 关闭上下文
        UIGraphicsEndImageContext()
        
        return image
    }
    
    
    
    // MARK: - ************压缩图片
    func getImageScale(width: CGFloat) -> UIImage {
        
        ///------ 判断,如果当前图片宽度小于程序员指定的宽度
        if self.size.width < width {
            return self
        }
        
        ///------ 获取图片的最终高度
        let height = (width*self.size.height)/self.size.width
        
        ///------ 设置rect
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        
        ///------ 开启上下文
        UIGraphicsBeginImageContext(rect.size)
        
        ///------ 将图片渲染到上下文中
        self.drawInRect(rect)
        
        ///------ 从上下文获取image
        let result = UIGraphicsGetImageFromCurrentImageContext()
        
        ///------ 关闭上下文
        UIGraphicsEndImageContext()
        
        return result
    }
    
    
    
    
    
    
}
